import React, { useCallback, useEffect, useMemo } from 'react';
import { EnvironmentalSensor, PowerDevice, HVACDevice, FireDevice } from '../../../types';
import EnvironmentalSensorComponent from './EnvironmentalSensor';
import PowerDeviceComponent from './PowerDevice';
import HVACDeviceComponent from './HVACDevice';
import FireDeviceComponent from './FireDevice';

interface FacilityManagerProps {
  environmentalSensors?: EnvironmentalSensor[];
  powerDevices?: PowerDevice[];
  hvacDevices?: HVACDevice[];
  fireDevices?: FireDevice[];
  onDeviceClick?: (deviceId: string, deviceType: string) => void;
  selectedDeviceId?: string;
}

/**
 * 设施管理器组件 - 负责渲染和管理所有环境设备
 * @param environmentalSensors 环境传感器数据
 * @param powerDevices 电力设备数据
 * @param hvacDevices HVAC设备数据
 * @param fireDevices 消防设备数据
 * @param onDeviceClick 设备点击回调
 * @param selectedDeviceId 当前选中的设备ID
 */
const FacilityManager: React.FC<FacilityManagerProps> = ({
  environmentalSensors = [],
  powerDevices = [],
  hvacDevices = [],
  fireDevices = [],
  onDeviceClick,
  selectedDeviceId
}) => {
  // 处理设备点击事件
  const handleDeviceClick = useCallback((deviceId: string, deviceType: string) => {
    if (onDeviceClick) {
      onDeviceClick(deviceId, deviceType);
    }
  }, [onDeviceClick]);

  // 检查设备状态并生成警报
  const checkDeviceStatuses = useCallback(() => {
    const alerts: { id: string; type: string; severity: string }[] = [];

    // 检查环境传感器
    environmentalSensors.forEach(sensor => {
      if (sensor.status === 'critical') {
        alerts.push({
          id: sensor.id,
          type: 'environmental',
          severity: 'critical'
        });
      } else if (sensor.status === 'warning') {
        alerts.push({
          id: sensor.id,
          type: 'environmental',
          severity: 'warning'
        });
      }
    });

    // 检查电力设备
    powerDevices.forEach(device => {
      if (device.status === 'error') {
        alerts.push({
          id: device.id,
          type: 'power',
          severity: 'critical'
        });
      } else if (device.status === 'warning') {
        alerts.push({
          id: device.id,
          type: 'power',
          severity: 'warning'
        });
      }
    });

    // 检查HVAC设备
    hvacDevices.forEach(device => {
      if (device.status === 'error') {
        alerts.push({
          id: device.id,
          type: 'hvac',
          severity: 'critical'
        });
      } else if (device.status === 'warning') {
        alerts.push({
          id: device.id,
          type: 'hvac',
          severity: 'warning'
        });
      }
    });

    // 检查消防设备
    fireDevices.forEach(device => {
      if (device.status === 'activated') {
        alerts.push({
          id: device.id,
          type: 'fire',
          severity: 'critical'
        });
      } else if (device.status === 'warning') {
        alerts.push({
          id: device.id,
          type: 'fire',
          severity: 'warning'
        });
      }
    });

    return alerts;
  }, [environmentalSensors, powerDevices, hvacDevices, fireDevices]);

  // 生成设备布局（自动布局）
  const generateDeviceLayout = useCallback((devices: any[], type: string) => {
    const positions: { x: number; y: number; z: number }[] = [];
    
    // 根据设备类型和数量生成合理的布局
    switch (type) {
      case 'environmental':
        // 环境传感器通常安装在天花板
        devices.forEach((_, index) => {
          const angle = (index / devices.length) * Math.PI * 2;
          const radius = Math.max(5, devices.length * 1.5);
          positions.push({
            x: Math.cos(angle) * radius,
            y: 4,
            z: Math.sin(angle) * radius
          });
        });
        break;
      case 'power':
        // 电力设备通常安装在机房角落
        const powerPositions = [
          { x: -8, y: 1, z: -12 },
          { x: 8, y: 1, z: -12 },
          { x: -8, y: 1, z: 12 },
          { x: 8, y: 1, z: 12 }
        ];
        devices.forEach((_, index) => {
          positions.push(powerPositions[index % powerPositions.length]);
        });
        break;
      case 'hvac':
        // HVAC设备通常安装在墙壁附近
        const hvacPositions = [
          { x: -9, y: 1, z: 0 },
          { x: 9, y: 1, z: 0 },
          { x: 0, y: 1, z: -14 },
          { x: 0, y: 1, z: 14 }
        ];
        devices.forEach((_, index) => {
          positions.push(hvacPositions[index % hvacPositions.length]);
        });
        break;
      case 'fire':
        // 消防设备分布在机房各处
        devices.forEach((_, index) => {
          const angle = (index / devices.length) * Math.PI * 2;
          const radius = Math.max(7, devices.length * 2);
          positions.push({
            x: Math.cos(angle) * radius,
            y: 3,
            z: Math.sin(angle) * radius
          });
        });
        break;
      default:
        devices.forEach((_, index) => {
          positions.push({ x: index * 2, y: 1, z: 0 });
        });
    }
    
    return positions;
  }, []);

  // 使用useMemo缓存警报列表，避免每次渲染都重新计算
  const alerts = useMemo(() => {
    return checkDeviceStatuses();
  }, [checkDeviceStatuses]);
  
  // 当设备数据变化时更新警报
  useEffect(() => {
    // 设置定期检查
    const intervalId = setInterval(checkDeviceStatuses, 30000); // 每30秒检查一次
    
    return () => {
      clearInterval(intervalId);
    };
  }, [checkDeviceStatuses]);

  // 渲染环境传感器 - 使用useMemo缓存结果
  const renderedEnvironmentalSensors = useMemo(() => {
    const positions = generateDeviceLayout(environmentalSensors, 'environmental');
    
    return environmentalSensors.map((sensor, index) => {
      // 如果传感器没有位置，使用生成的位置
      const position = sensor.position || positions[index] || { x: 0, y: 0, z: 0 };
      const sensorWithPosition = { ...sensor, position };
      
      return (
        <EnvironmentalSensorComponent
          key={sensor.id}
          sensor={sensorWithPosition}
          isSelected={selectedDeviceId === sensor.id}
          onClick={() => handleDeviceClick(sensor.id, 'environmental')}
        />
      );
    });
  }, [environmentalSensors, selectedDeviceId, handleDeviceClick, generateDeviceLayout]);

  // 渲染电力设备 - 使用useMemo缓存结果
  const renderedPowerDevices = useMemo(() => {
    const positions = generateDeviceLayout(powerDevices, 'power');
    
    return powerDevices.map((device, index) => {
      const position = device.position || positions[index] || { x: 0, y: 0, z: 0 };
      const deviceWithPosition = { ...device, position };
      
      return (
        <PowerDeviceComponent
          key={device.id}
          device={deviceWithPosition}
          isSelected={selectedDeviceId === device.id}
          onClick={() => handleDeviceClick(device.id, 'power')}
        />
      );
    });
  }, [powerDevices, selectedDeviceId, handleDeviceClick, generateDeviceLayout]);

  // 渲染HVAC设备 - 使用useMemo缓存结果
  const renderedHvacDevices = useMemo(() => {
    const positions = generateDeviceLayout(hvacDevices, 'hvac');
    
    return hvacDevices.map((device, index) => {
      const position = device.position || positions[index] || { x: 0, y: 0, z: 0 };
      const deviceWithPosition = { ...device, position };
      
      return (
        <HVACDeviceComponent
          key={device.id}
          device={deviceWithPosition}
          isSelected={selectedDeviceId === device.id}
          onClick={() => handleDeviceClick(device.id, 'hvac')}
        />
      );
    });
  }, [hvacDevices, selectedDeviceId, handleDeviceClick, generateDeviceLayout]);

  // 渲染消防设备 - 使用useMemo缓存结果
  const renderedFireDevices = useMemo(() => {
    const positions = generateDeviceLayout(fireDevices, 'fire');
    
    return fireDevices.map((device, index) => {
      const position = device.position || positions[index] || { x: 0, y: 0, z: 0 };
      const deviceWithPosition = { ...device, position };
      
      return (
        <FireDeviceComponent
          key={device.id}
          device={deviceWithPosition}
          isSelected={selectedDeviceId === device.id}
          onClick={() => handleDeviceClick(device.id, 'fire')}
        />
      );
    });
  }, [fireDevices, selectedDeviceId, handleDeviceClick, generateDeviceLayout]);

  return (
    <group>
      {/* 渲染环境传感器 */}
      {renderedEnvironmentalSensors}
      
      {/* 渲染电力设备 */}
      {renderedPowerDevices}
      
      {/* 渲染HVAC设备 */}
      {renderedHvacDevices}
      
      {/* 渲染消防设备 */}
      {renderedFireDevices}
    </group>
  );
};

export default React.memo(FacilityManager);